//
//  AddressAddViewController.m
//  何五路
//
//  Created by _ADY on 15/7/1.
//  Copyright (c) 2015年 _ADY. All rights reserved.
//

#import "AddressAddViewController.h"

@interface AddressAddViewController ()

@end
static LoadingView *loading = nil;
#define AddAddHight 40
@implementation AddressAddViewController
@synthesize mTableView,addDictionary;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"新建收货地址";
        self.view.backgroundColor = bgColor;
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
    self.navigationItem.backBarButtonItem = item;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStylePlain target:self action:@selector(rightAction)];
    
    mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenMySize.size.width, screenMySize.size.height)];
    mTableView.delegate = self;
    mTableView.dataSource = self;
    mTableView.sectionHeaderHeight = 0.0;
    mTableView.sectionFooterHeight = 0.0;
    mTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:mTableView];
    
    UIView *v = [[UIView alloc] initWithFrame:CGRectZero];//清除多余分割线
    [mTableView setTableFooterView:v];
    
    bgNameArray = [NSArray arrayWithObjects:@"收货人姓名",@"手机号码",@"电话号码",@"邮政编码",@"",@"",@"详细地址", nil];
    addDictionary = [NSMutableDictionary dictionaryWithCapacity:10];
}
//Address.Id=0&Address.Name=收货人姓名&Address.StateProvinceId=省份ID&Address.CityId=城市ID&Address.DistrictId=县区ID&Address.StreetId=街道ID&Address.Address1=详细地址&Address.ZipPostalCode=邮政编码&Address.CellphoneNumber=手机号码&Address.PhoneNumber=电话号码
#pragma mark 保存
-(void)rightAction
{
    NSArray *mArray = [NSArray arrayWithObjects:@"收货人姓名不能为空！",@"手机号码不能为空！",@"电话号码不能为空！",@"邮政编码不能为空！",@"",@"",@"详细地址不能为空！", nil];
    for (int i = 0 ; i < mArray.count; i ++)
    {
        if (i == 2 || i == 4 || i == 5) {
            continue;
        }
        UITextField *Field1 = (UITextField *)[self.view viewWithTag:i+1];
        if (Field1.text.length == 0) {
            [SendService alerViewMessage:[mArray objectAtIndex:i]];
            return;
        }
    }
    UILabel *tLabel = (UILabel *)[self.view viewWithTag:5];
    if ([tLabel.text isEqualToString:@"省、市、区"] ) {
         [SendService alerViewMessage:@"省、市、区不能为空！"];
        return;
    }
    UITextField *Field2 = (UITextField *)[self.view viewWithTag:2];
    if (![SendService validateMobile:Field2.text]) {
        [SendService alerViewMessage:@"请输入正确的手机号码！"];
        return;
    }
    NSMutableDictionary *postDic1 = [[NSMutableDictionary alloc] init];
    
    
    UITextField *Field1 = (UITextField *)[self.view viewWithTag:1];
    [postDic1 setObject:Field1.text forKey:@"Address.Name"];
    

    
    [postDic1 setObject:[[CountryArray objectAtIndex:CountryInt] objectForKey:@"id"] forKey:@"Address.StateProvinceId"];
    [postDic1 setObject:[[ProvinceArray objectAtIndex:ProvinceInt] objectForKey:@"id"] forKey:@"Address.CityId"];
    [postDic1 setObject:[[CityArray objectAtIndex:CityInt] objectForKey:@"id"] forKey:@"Address.DistrictId"];
    
    UILabel *t1Label = (UILabel *)[self.view viewWithTag:6];
    if ([t1Label.text isEqualToString:@"街道"] ) {
        [postDic1 setObject:@"" forKey:@"Address.StreetId"];
    }
    else
        [postDic1 setObject:[[DistrictArray objectAtIndex:DistrictInt] objectForKey:@"id"] forKey:@"Address.StreetId"];
    
     UITextField *Field4 = (UITextField *)[self.view viewWithTag:7];
    [postDic1 setObject:Field4.text forKey:@"Address.Address1"];
    UITextField *Field7 = (UITextField *)[self.view viewWithTag:4];
    [postDic1 setObject:Field7.text forKey:@"Address.ZipPostalCode"];
    
    
    [postDic1 setObject:Field2.text forKey:@"Address.CellphoneNumber"];
    UITextField *Field3 = (UITextField *)[self.view viewWithTag:3];
    if (Field3.text.length != 0)
        [postDic1 setObject:Field3.text forKey:@"Address.PhoneNumber"];
    else
        [postDic1 setObject:@"" forKey:@"Address.PhoneNumber"];
    [postDic1 setObject:@"0" forKey:@"Address.Id"];
    
    loading = [[LoadingView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:loading];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *myArray = [SendService AddressAdd:postDic1];
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"新建收货地址 %@",myArray);
            if ([[NSString stringWithFormat:@"%@",[myArray objectForKey:@"Result"]] isEqualToString:@"success"])
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[myArray objectForKey:@"Message"]  delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
                [alert show];
                
                
            }
            else
                [SendService alerViewMessage:[myArray objectForKey:@"Message"]];
            [loading closeLoading];
        });
    });
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [[NSNotificationCenter defaultCenter] postNotificationName:KAddressUpdate object:self];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 7;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return AddAddHight;
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"AddressAddCell";
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        aTableView.showsVerticalScrollIndicator = NO;
//        cell.tintColor = [UIColor colorWithRed:243/255.0 green:125/255.0 blue:125/255.0 alpha:1];//勾选颜色
    }
    int i = (int)[[cell.contentView subviews] count] - 1;
    for(;i >= 0 ; i--)
    {
        [[[cell.contentView subviews] objectAtIndex:i] removeFromSuperview];
    }
    aTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;

    CGRect mFrame = cell.contentView.frame;
    mFrame.origin.x = mFrame.origin.x+10;
    mFrame.size.width = mFrame.size.width-20;
    
    if (indexPath.row == 4)
    {
        [cell.contentView addSubview:[self setFrame:mFrame setTitle:@"省、市、区" setFont:[UIFont fontWithName:@"Arial" size:labelSize] setColor:[UIColor blackColor] setTag:indexPath.row+1]];
    }
    else if (indexPath.row == 5)
    {
        
        [cell.contentView addSubview:[self setFrame:mFrame setTitle:@"街道" setFont:[UIFont fontWithName:@"Arial" size:labelSize] setColor:[UIColor blackColor] setTag:indexPath.row+1]];
    }
    else
        [cell.contentView addSubview:[self setFrame:mFrame setTitle:@"" setTag:indexPath.row+1]];
    
    // Configure the cell...
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    if (indexPath.row == 4)
    {
        
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
        if (addressPicker == nil)
        {
        
            [self remArray];
            addressPicker=[[UIPickerView alloc] initWithFrame:CGRectMake(0, screenMySize.size.height, screenMySize.size.width, screenMySize.size.width*2/3)];
            addressPicker.delegate = self;
            addressPicker.showsSelectionIndicator = YES;//选中条
            [self.view addSubview: addressPicker];
            
            [self after];
        }
        
        [self gotoPicker];
        
    }
    else if (indexPath.row == 5)
    {
        [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
        if (CityArray.count == 0 || DistrictArray.count == 0)
        {
            [SendService alerViewMessage:@"暂无街道地址！"];
        }
        else
        {
            if (addressJPicker == nil)
            {
                addressJPicker=[[UIPickerView alloc] initWithFrame:CGRectMake(0, screenMySize.size.height, screenMySize.size.width, screenMySize.size.width*2/3)];
                addressJPicker.delegate = self;
                addressJPicker.showsSelectionIndicator = YES;//选中条
                [self.view addSubview: addressJPicker];
            }
            [self gotoJpicker];

        }
    }
}

-(void)moveAllPicker
{
    addressJPicker.alpha = 0;
    addressPicker.alpha = 0;
}
-(void)gotoPicker
{
    addressJPicker.alpha = 0;
    addressPicker.alpha = 1;
    [UIView animateWithDuration:0.7 animations:^{
        addressPicker.frame = CGRectMake(0, screenMySize.size.height-screenMySize.size.width*2/3, screenMySize.size.width, screenMySize.size.width*2/3);
    }];
}

-(void)gotoJpicker
{
    addressPicker.alpha = 0;
    addressJPicker.alpha = 1;
    [UIView animateWithDuration:0.7 animations:^{
        addressJPicker.frame = CGRectMake(0, screenMySize.size.height-screenMySize.size.width*2/3, screenMySize.size.width, screenMySize.size.width*2/3);
    }];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if (addressPicker == pickerView)
        return 3;
    else if (addressJPicker == pickerView)
        return 1;
    return YES;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (addressPicker == pickerView)
    {
        if (component==0) {
            return [CountryArray count];
        }
        else if (component==1)
        {
            return [ProvinceArray count];//划分picker中有多少行
        }
        else if (component==2)
        {
            return [CityArray count];
        }
    }
    else if (addressJPicker == pickerView)
    {
        return [DistrictArray count];
    }

    return	YES;
}

//在picker中输出内容
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (addressPicker == pickerView)
    {
        if (component==0)
        {
            return [[CountryArray objectAtIndex:row] objectForKey:@"name"];
        }
        else if (component==1)
        {
            return [[ProvinceArray objectAtIndex:row] objectForKey:@"name"];
        }
        else if (component==2)
        {
            return [[CityArray objectAtIndex:row] objectForKey:@"name"];
        }
    }
    else if (addressJPicker == pickerView)
    {
        return [[DistrictArray objectAtIndex:row] objectForKey:@"name"];
    }
    return nil;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{

    if (addressPicker == pickerView)
    {
        if (component==0)
        {
            
            //第二列默认选择第一行
            [pickerView selectRow:0 inComponent:1 animated:YES];
            [pickerView selectRow:0 inComponent:2 animated:YES];
            CountryInt =row;
            [self after1];
        }
        else if (component==1)
        {
            
            [pickerView selectRow:0 inComponent:2 animated:YES];
//            [pickerView reloadComponent:2];
            ProvinceInt =row;
            [self after2];

        }
        else  if (component==2)
        {
            CityInt = row;
            [self setLabel];
            [self after3];
        }
    }
    else if (addressJPicker == pickerView)
    {
        DistrictInt  = row;
        [self setJLabel];
    }
}

//文字居中
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    UILabel *retval = (id)view;
    if(!retval)
    {
        retval = [[UILabel alloc] initWithFrame:CGRectMake(12.0f, 0.0f, [pickerView rowSizeForComponent:component].width-12, [pickerView rowSizeForComponent:component].height)];
        
    }
    retval.font = [UIFont boldSystemFontOfSize:labelSize];
    retval.backgroundColor = [UIColor clearColor];
    retval.textAlignment = 1;
    if (pickerView ==addressPicker)
    {
        if (component == 0)
            retval.text = [[CountryArray objectAtIndex:row] objectForKey:@"name"];
        if (component == 1)
            retval.text = [[ProvinceArray objectAtIndex:row] objectForKey:@"name"];
        if (component == 2)
            retval.text = [[CityArray objectAtIndex:row] objectForKey:@"name"];
    }
    else if (addressJPicker == pickerView)
        retval.text = [[DistrictArray objectAtIndex:row] objectForKey:@"name"];

    return retval;
}

-(void)setLabel
{
    UILabel *tLabel = (UILabel *)[self.view viewWithTag:5];
    if (CityArray.count != 0) {
        tLabel.text = [NSString stringWithFormat:@"%@%@%@",[[CountryArray objectAtIndex:CountryInt] objectForKey:@"name"],[[ProvinceArray objectAtIndex:ProvinceInt] objectForKey:@"name"],[[CityArray objectAtIndex:CityInt] objectForKey:@"name"]];
    }
}

-(void)setJLabel
{
    UILabel *tLabel = (UILabel *)[self.view viewWithTag:6];
    if (DistrictArray.count != 0) {
        tLabel.text = [NSString stringWithFormat:@"%@",[[DistrictArray objectAtIndex:DistrictInt] objectForKey:@"name"]];
    }
    else
    {
        tLabel.text = @"街道";
    }
}

-(void)remArray
{
    if (CountryArray != nil) {
        [CountryArray removeAllObjects];
        CountryArray = nil;
    }
    CountryArray = [[NSMutableArray alloc] init];
    
    if (ProvinceArray != nil) {
        [ProvinceArray removeAllObjects];
        ProvinceArray = nil;
    }
    ProvinceArray = [[NSMutableArray alloc] init];
    
    if (CityArray != nil) {
        [CityArray removeAllObjects];
        CityArray = nil;
    }
    CityArray = [[NSMutableArray alloc] init];
    
    if (DistrictArray != nil) {
        [DistrictArray removeAllObjects];
        DistrictArray = nil;
    }
    DistrictArray = [[NSMutableArray alloc] init];
}
-(void)after
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService GetStatesByCountryId];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret !=nil)
            {
                CountryArray = [ret objectForKey:@"Entity"];
            }
            CountryInt = 0;
            [self after1];
            
        });
    });
}

-(void)after1
{
    NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
    [postDic setObject:[[CountryArray objectAtIndex:CountryInt] objectForKey:@"id"] forKey:@"provinceId"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService GetCityByProvinceId:postDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (ret !=nil)
            {
                ProvinceArray = [ret objectForKey:@"Entity"];
            }
            ProvinceInt = 0;
             [self after2];
            
        });
    });
    
}

-(void)after2
{
    NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
    [postDic setObject:[[ProvinceArray objectAtIndex:ProvinceInt] objectForKey:@"id"] forKey:@"cityId"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService GetDistrictByCityId:postDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (ret !=nil)
            {
                CityArray = [ret objectForKey:@"Entity"];
            }
            CityInt = 0;
            [addressPicker reloadAllComponents];
            [self setLabel];
            [self after3];
            
        });
    });
    
}

-(void)after3
{
    NSMutableDictionary *postDic = [[NSMutableDictionary alloc] init];
    [postDic setObject:[[CityArray objectAtIndex:CityInt] objectForKey:@"id"] forKey:@"districtId"];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        NSDictionary *ret = [SendService GetStreetByDistrictId:postDic];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (ret !=nil)
            {
                DistrictArray = [ret objectForKey:@"Entity"];
            }
            DistrictInt = 0;
            [addressJPicker reloadAllComponents];
            [self setJLabel];
        });
    });
    
}


-(UILabel*)setFrame:(CGRect)frame setTitle:(NSString*)title setFont:(UIFont*)font setColor:(UIColor*)myColor setTag:(int)tag
{
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:frame];
    if (title != nil)
        titleLabel.text = [NSString stringWithFormat:@"%@",title];
    titleLabel.textAlignment = 0;
//    titleLabel.numberOfLines = 0;
    titleLabel.font = font;
    titleLabel.tag =tag;
    titleLabel.textColor = myColor;
    return titleLabel;
}

-(UITextField*)setFrame:(CGRect)frame setTitle:(NSString*)title setTag:(int)Tag
{
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    [textField setFont:[UIFont systemFontOfSize:labelSize]];
    textField.returnKeyType = UIReturnKeyDefault;
    if (Tag ==1 || Tag ==7) {
        textField.keyboardType = UIKeyboardTypeDefault;
    }
    else
        textField.keyboardType = UIKeyboardTypeNumberPad;
    textField.delegate = self;
    textField.text = [NSString stringWithFormat:@"%@",title];
    textField.textAlignment = 0;
    textField.tag = Tag;
    [textField setPlaceholder:[bgNameArray objectAtIndex:Tag-1]];

    return textField;
}

//- (BOOL)textField:(UITextField *)text1Field shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    
//    NSString *text = [text1Field.text stringByReplacingCharactersInRange:range withString:string];
//    //    if (type < minInt || type > maxInt)
//    //    {
//    //        text1Field.text = [text1Field.text substringToIndex:[text1Field.text length] - 1];
//    //    }
//    return YES;
//}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    mTableView.frame =CGRectMake(0, 0, screenMySize.size.width, screenMySize.size.height-screenMySize.size.width*2/3-50);
    [self moveAllPicker];
    [textField resignFirstResponder];
    return YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
